import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../entity/main/xmm_tab_bar_item.dart';

class XmmBottomNavigationBar extends StatefulWidget {
  const XmmBottomNavigationBar(
      {Key? key, required this.tabItems, required this.tabPages})
      : super(key: key);

  final List<XmmTabBarItem> tabItems;

  final List<Widget> tabPages;

  @override
  State<StatefulWidget> createState() => _XmmBottomNavigationBarState();
}

class _XmmBottomNavigationBarState extends State<XmmBottomNavigationBar> {
  // 当前子项索引
  final _selectIndex = 0.obs;

  //默认为0，可以不填写
  final PageController _controller = PageController(initialPage: 0);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBody: true,
      bottomNavigationBar: Obx(
        () => Container(
          margin: const EdgeInsets.only(left: 20, right: 20, bottom: 33),
          height: 63,
          child: Card(
            elevation: 5,
            shadowColor: const Color(0x44000000),
            shape: const RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(34))),
            child: Row(children: _getTabItemList()),
          ),
        ),
      ),
      body: PageView(
        controller: _controller,
        //设置不可滑动
        physics: const NeverScrollableScrollPhysics(),
        children: widget.tabPages,
      ),
    );
  }

  List<Widget> _getTabItemList() {
    var tabItemList = <Widget>[];
    for (int i = 0; i < widget.tabItems.length; i++) {
      String icon;
      if (i == _selectIndex.value) {
        icon = widget.tabItems.elementAt(i).selectIcon;
      } else {
        icon = widget.tabItems.elementAt(i).normalIcon;
      }
      tabItemList.add(_getTabItem(icon, i));
    }
    return tabItemList;
  }

  // 获取项目 icon
  Widget _getTabItem(String icon, int index) {
    return Expanded(
      child: GestureDetector(
        child: Image.asset(icon, width: 24, height: 24),
        onTap: () {
          _selectIndex.value = index;
          _controller.jumpToPage(index);
        },
      ),
    );
  }
}
